using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using Network.Tcp.Awaitable;

namespace Network.Tcp.Pooling
{
    /// <summary>
    /// 中间人对象池
    /// </summary>
    public class AwaiterPool : ObjectPool<Awaiter>
    {
        private Func<Awaiter> _createMethod;
        private Action<Awaiter> _cleanMethod;

        #region 初始化Awaiter池
        public AwaiterPool Initialize(Func<Awaiter> createMethod, Action<Awaiter> cleanMethod, int initialCount = 0)
        {
            //创建对象的方法            
            _createMethod = createMethod ?? throw new ArgumentNullException("创建SocketAsyncEventArgs方法不能为空");
            //清理对象的方法
            _cleanMethod = cleanMethod ?? throw new ArgumentNullException("清理SocketAsyncEventArgs方法不能为空");

            //初始数量不能小于0，否则报错
            if (initialCount < 0)
                throw new ArgumentOutOfRangeException("initialCount", initialCount, "初始化数量不能小于0");
            //按指定数量创建对象
            for (int i = 0; i < initialCount; i++)
            {
                Add(Create());
            }
            return this;
        }
        #endregion
        #region 创建对象
        protected override Awaiter Create()
        {
            return _createMethod();
        }
        #endregion
        #region 清理对象并返回到对象池
        public void Return(Awaiter saea)
        {
            _cleanMethod(saea);
            Add(saea);
        }
        #endregion
    }
}
